<template>
  <div class="s-table-container">
    <s-search
      :form="props.form"
      class="search-container"
      ref="search"
      :refresh="refresh"
    ></s-search>
    <slot name="operator" />
    <div class="s-table-header">
      <a-table
        :dataSource="tableData"
        :columns="props.columns"
        :scroll="{ x: '100%', y: height }"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :bordered="true"
      >
        <template #bodyCell="scope">
          <template v-if="scope.column.dataIndex === 'action'">
            <slot name="operations" :scope="{ row: scope.record }" />
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, onMounted, computed } from "vue";
import "./index.css";

const props = defineProps({
  form: {
    type: Array,
    default: () => [],
  },
  columns: {
    type: Array,
    required: true,
  },
  loadData: {
    type: Function,
    required: true,
  },
});

onMounted(() => {
  init(formState.value);
});

const tableData = ref([]);
const search = ref();
const height = ref(window.innerHeight - 350);
const loading = ref(false);
const formState = ref({
  page: 1,
  pageSize: 10,
});
const total = ref(0);
const pagination = computed(() => ({
  pageSizeOptions: ["10", "20", "50", "100"],
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (thisTotal) => `共 ${thisTotal} 条`,
  current: formState.value.page,
  pageSize: formState.value.pageSize,
  size: "middle",
  total: total.value,
}));

const init = async (params) => {
  loading.value = true;
  const result = await props.loadData(params);
  tableData.value = result.data;
  total.value = result.total;
  loading.value = false;
};

const handleTableChange = (pagination) => {
  formState.value.page = pagination.current;
  formState.value.pageSize = pagination.pageSize;
  init({ ...formState.value, ...search.value.formState });
};

const refresh = (label, values) => {
  if (label == "重置" || label == "" || label == null) {
    formState.value = { page: 1, pageSize: 10 };
  } else {
    formState.value = { ...formState.value, ...values };
  }
  init(formState.value);
};

defineExpose({
  refresh,
});
</script>
